#!/usr/bin/ruby

=begin
Copyright (c) 2008, Pat Sissons
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
    * Neither the name of the DHX Software nor the names of its contributors may
      be used to endorse or promote products derived from this software without 
      specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=end

require 'optparse'
require 'thread'
require 'log4r/configurator'

require 'ConfigFile.rb'
require 'Show.rb'
require 'Feed.rb'

require 'log4r'
include Log4r

module Kernel
    private
    def methname
        caller[2] =~ /`([^']*)'/ and $1
    end
end

class RubyRssDownloader
    attr_reader :logger, :conf, :shows, :feeds, :mut, :rxSeasonEp, :rxReject, :torTimeout

    $VERSION = '0.3b'

    def initialize(args)
        begin
            Configurator.load_xml_file('log4r_config.xml')
            @logger = Logger["screen::file"].nil? ? Logger.root : Logger["screen::file"]
            @logger.ftrace {'ENTER'}
            @mut = Mutex.new
            params = {'file' => '~/.rrssdlrc'}

            OptionParser.new do |opts|
                opts.banner =
<<EOF
Ruby RSS Feed Downloader (TV Show Edition) v#{$VERSION}

Usage: rrssdl [options]

Options:
    -h | --help         show this help text
    -d | --debug        set debug mode (blank is ON, default is OFF)
    -v | --verbose      set verbose mode (blank is ON, default is OFF)
    -q | --quiet        disable all logging to screen (log file is still used if defined)
    -c | --config path  set config file using path (default is ~/.rrssdlrc)
    -D | --daemon       run as a daemon (SIGINT exist, SIGHUP reloads config)
EOF

                opts.on('-h', '--help') do 
                    puts opts.banner
                    exit(0)
                end
                opts.on('-d', '--debug') do
                    params['debug'] = true
                    @logger.info {"DEBUG = 'ON'"}
                end
                opts.on('-v', '--verbose') do
                    params['verbose'] = true
                    @logger.info {"VERBOSE = 'ON'"}
                end
                opts.on('-q', '--quiet') do
                    params['quiet'] = true
                end

                opts.on('-c', '--config [ARG]') do |c| 
                    params['file'] = c
                    @logger.info {"Config Path = #{c}"}
                end
                opts.on('-D', '--daemon') do
                    params['daemon'] = true
                    @logger.info {"DAEMON MODE = 'ON'"}
                end
            end.parse!(args)
        rescue => e
            @logger.error {"Option Parser Error: #{e}"}
        end

        @conf = ConfigFile.new(self)
        @conf.init_params(params)

        init_settings
        @logger.ftrace {'LEAVE'}
    end

    def te
        @logger.ftrace {"ENTER '#{methname}'"}
    end

    def tl
        @logger.ftrace {"LEAVE '#{methname}'"}
    end

    def init_settings
        @logger.ftrace {'ENTER'}
        @logger.debug {"Initializing In-Memory Settings"}
        @shows = Hash.new
        @feeds = Hash.new

        @logger.info {'Building Feed Collection...'}
        @conf.get_list('enabled_feed_ids').each do |f|
            fi = @conf.get_list(f)
            if fi.length < 1
                @logger.error {"Poorly formed feed line [#{f}]"}
                next
            end
            @feeds[f] = Feed.new(self, f, fi.shift, fi)
            @logger.debug {@feeds[f].to_s.strip}
        end

        @logger.info {'Building Show Collection...'}
        @conf.get_list('enabled_show_ids').each do |s|
            si = @conf.get_list(s)
            if si.length < 3
                @logger.error {"Poorly formed show line [#{s}]"}
                next
            end
            @shows[s] = Show.new(self, s, si.shift, si.shift, si.shift, si)
            @logger.debug(@shows[s].to_s.strip)
        end
        
        @rxSeasonEp = conf.get_list('season_ep_regex')
        @rxReject = conf.get_list('reject_regex')
        @torTimeout = conf.has_key?('torrent_dl_timeout_seconds') ? conf['torrent_dl_timeout_seconds'].to_i : 60

        begin
            Dir.mkdir(conf['download_path']) unless File.directory?(conf['download_path'])
            Dir.mkdir(conf['download_path_review']) unless File.directory?(conf['download_path_review'])
        rescue => e
            @logger.error {"Directory Creation Error: #{e}"}
        end

        load_state
        @logger.ftrace {'LEAVE'}
        nil
    end

    def load_state
        @logger.ftrace {'ENTER'}
        @logger.notice {'Loading State File...'}
        @state = ConfigFile.new(self)
        @state.file = @conf['state_file']
        @state.read_file
        @state.each_key do |k|
            next unless @shows.has_key?(k)
            si = @state.get_list(k)
            @logger.debug {"Loading State Item: #{k} = #{si}"}
            @shows[k].load_state(si)
        end
        @logger.ftrace {'LEAVE'}
        nil
    end

    def save_state
        @logger.ftrace {'ENTER'}
        @logger.notice {'Saving State File...'}
        @shows.each_value do |s|
            @logger.debug {"Saving State Item: #{s.id} = #{s.get_state}"}
            @state[s.id] = s.get_state
        end
        @state.write_file
        @logger.ftrace {'LEAVE'}
        nil
    end

    def refresh_feeds
        @logger.ftrace {'ENTER'}
        @logger.info {'Refreshing Feeds...'}
        @feeds.each_value do |f|
            f.sync_refresh_feed
        end
        @logger.info {'Feeds Refreshed'}
        @logger.ftrace {'LEAVE'}
        nil
    end

    def run
        @logger.ftrace {'ENTER'}
        # catch Ctrl-C (Exit)
        Kernel.trap('INT') do
            save_state
            @logger.notice {'Exiting...'}
            exit(0)
        end
        
        # catch SIGHUP
        Kernel.trap('HUP') do
            @logger.notice {'Reloading Config...'}
            # kill all feed timers
            @feeds.each_value do |f|
                f.enabled = false
            end
            @conf.read_file
            init_settings
            refresh_feeds
        end

        # force initial refresh
        refresh_feeds

        if @conf.has_key?('daemon')
            @logger.notice {'Daemonizing...'}
            pid = fork do
                main_loop
            end
            if (pid > 0)
                @logger.notice {"Daemon PID = #{pid}"}
                Process.detach(pid)
            end
        else
            main_loop
        end
        @logger.ftrace {'LEAVE'}
        nil
    end

    def main_loop
        @logger.ftrace {'ENTER'}
        loop do
            sleep 60
        end
        @logger.ftrace {'LEAVE'}
        nil
    end
end

rss = RubyRssDownloader.new($ARGV)
rss.run
